package com.crazy.base.common.utils.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

@Slf4j
public class EasyReadListener<T> implements ReadListener<T> {

    private final Validator validator;

    @Getter
    private List<T> dataList;

    public EasyReadListener(Validator validator) {
        this.validator = validator;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        Set<ConstraintViolation<T>> constraintViolationSet = validator.validate(t);
        if (!constraintViolationSet.isEmpty()) {
            handleError(constraintViolationSet, t);
        }
        T t1 = beforeAdd(t);
        dataList.add(t1);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("读取完成");
    }

    protected void handleError(Set<ConstraintViolation<T>> constraintViolationSet, T t) {
        log.info("暂时不做任何处理");
    }

    protected T beforeAdd(T t) {
        return t;
    }

}
